登录 白背景

1022. 从根到叶的二进制数之和

https://leetcode.cn/problems/sum-of-root-to-leaf-binary-numbers/

  • 提交时间:2022-05-30 08:26:25
  • 执行用时:8 ms, 在所有 PHP 提交中击败了60.00%的用户
  • 内存消耗:19.1 MB, 在所有 PHP 提交中击败了40.00%的用户
  • 通过测试用例:63 / 63
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($val = 0, $left = null, $right = null) {
 *         $this->val = $val;
 *         $this->left = $left;
 *         $this->right = $right;
 *     }
 * }
 */
class Solution {

    /**
     * @param TreeNode $root
     * @return Integer
     */
    function sumRootToLeaf($root) {
        return self::dfs($root, 0);
    }

    static function dfs($node, $val) {
        if ($node == null) {
            return $val;
        }
        $val = ($val << 1) | $node->val;
        if ($node->left == null && $node->right == null) {
            return $val;
        }

        $ret = 0;
        if ($node->left != null) {
            $ret += self::dfs($node->left, $val);
        }
        if ($node->right != null) {
            $ret += self::dfs($node->right, $val);
        }
        return $ret;
    }
}